package com.osfw.system.cotroller.monitor;

import cn.dev33.satoken.stp.StpUtil;
import com.github.pagehelper.PageInfo;
import com.osfw.framework.annotation.Log;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.core.domain.RestfulResult;
import com.osfw.framework.enums.BusinessType;
import com.osfw.framework.enums.OnlineStatus;
import com.osfw.framework.utils.text.Convert;
import com.osfw.system.entity.monitor.SysUserOnline;
import com.osfw.system.service.monitor.ISysUserOnlineService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 在线用户监控
 */
@Controller
@RequestMapping("/osfw/system/monitor/online")
public class SysUserOnlineController extends BaseController {
    private String prefix = "osfw/system/monitor/online";

    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
//    private OnlineSessionDAO onlineSessionDAO;

    @RequiresPermissions("monitor:online:view")
    @GetMapping()
    public String online() {
        return prefix + "/online";
    }

    @RequiresPermissions("monitor:online:list")
    @PostMapping("/list")
    @ResponseBody
    public PageInfo list(SysUserOnline userOnline) {
        startPage(SysUserOnline.class);
        List<SysUserOnline> list = userOnlineService.selectUserOnlineList(userOnline);
        return getPageInfo(list);
    }

    @RequiresPermissions(value = {"monitor:online:batchForceLogout", "monitor:online:forceLogout"}, logical = Logical.OR)
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @PostMapping("/batchForceLogout")
    @ResponseBody
    public RestfulResult batchForceLogout(String ids) {
        for (String sessionId : Convert.toStrArray(ids)) {
            SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
            if (online == null) {
                return error("用户已下线");
            }
            /*OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
            if (onlineSession == null) {
                return error("用户已下线");
            }*/
            if (sessionId.equals(StpUtil.getTokenSession().getId())) {
                return error("当前登录用户无法强退");
            }
//            onlineSessionDAO.delete(onlineSession);
            online.setStatus(OnlineStatus.off_line);
            userOnlineService.saveOnline(online);
        }
        return success();
    }
}
